/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.boot.tasks;

import org.internna.iwebmvc.boot.StartupTask;
import org.internna.iwebmvc.dao.SecurityDAO;
import org.internna.iwebmvc.model.Role;
import org.internna.iwebmvc.model.User;
import org.internna.iwebmvc.utils.Assert;
import org.springframework.beans.factory.annotation.Required;

import org.springframework.transaction.annotation.Transactional;
import static org.internna.iwebmvc.utils.StringUtils.hasText;

/**
 * Creates those roles that are not obtained by entity scanning.
 *
 * @author Jose Noheda
 * @since 1.0
 */
@Transactional
public final class CreateRolesStartupTask implements StartupTask {

    public static final String ROLE_DEVELOPER = "ROLE_DEVELOPER";
    public static final String ROLE_ISSUE_CREATOR = "ROLE_ISSUE_CREATOR";

    private String rootUser;
    private SecurityDAO dao;

    /**
     * Spring injection point (REQUIRED)
     *
     * @param dao a non null instance
     */
    @Required public void setDao(SecurityDAO dao) {
        Assert.notNull(dao);
        this.dao = dao;
    }

    /**
     * Spring injection point (REQUIRED)
     *
     * @param rootUser a not empty string
     */
    @Required public void setRootUser(String rootUser) {
        if (!hasText(rootUser)) {
            throw new IllegalArgumentException("Root user must contain all application roles!");
        }
        this.rootUser = rootUser;
    }

    /**
     * Execute after the framework. The actual order is not very important.
     *
     * @return APPLICATION_ORDER
     */
    @Override public int order() {
        return APPLICATION_ORDER;
    }

    /**
     * Creates the required roles if neeeded and assign them to the
     */
    @Override public void execute() {
        Role authority = dao.findAuthority(ROLE_DEVELOPER);
        if (authority == null) {
            dao.createAuthority(ROLE_DEVELOPER);
            User root = dao.findUser(rootUser);
            Assert.notNull(root);
            root.addRole(dao.findAuthority(ROLE_DEVELOPER));
            dao.updateUser(root);
        }
    }

    /**
     * Task name
     *
     * @return "IWebJTracker role creation task"
     */
    @Override public String getTaskName() {
        return "IWebJTracker role creation task";
    }

}
